/**
 * 
 */
package bai1.com.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author nglehien Oct 28, 2012 - 9:11:14 PM
 */
public class MyConnection extends Thread {
	private Socket socket;
	private static int BUFFER_SIZE = 1024 * 4;

	public MyConnection(Socket socket) {
		this.socket = socket;
		
		start();
	}

	@Override
	public void run() {
		try {
			ObjectInputStream objectInputStream = new ObjectInputStream(
					socket.getInputStream());
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(
					socket.getOutputStream());

			File file = (File) objectInputStream.readObject();
			FileInputStream fileInputStream = new FileInputStream(file);
			FileOutputStream fileOutputStream = new FileOutputStream(
					"bai_01/host/" + file.getName());
			byte[] buffer = new byte[BUFFER_SIZE];
			int count = 0;
			int total = 0;
			while ((count = fileInputStream.read(buffer)) != -1) {
				fileOutputStream.write(buffer, 0, count);
				total += count;
			}
			objectOutputStream.writeObject("đã nhận được:" + total + "byte(s)");
			fileInputStream.close();
			fileOutputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		super.run();
	}
}
